package com.member.shop.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.enums.ActivityStatusEnum;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.enums.OrderTypeEnum;
import com.member.common.exception.ServiceException;
import com.member.common.utils.DateUtils;
import com.member.common.utils.OrderNoCreate;
import com.member.common.utils.StringUtils;
import com.member.common.utils.bean.BeanUtils;
import com.member.common.utils.uuid.IdUtils;
import com.member.shop.domain.*;
import com.member.shop.mapper.SysBizActivityEnrollMapper;
import com.member.shop.mapper.SysBizActivityMapper;
import com.member.shop.service.ISysBizActivityFieldService;
import com.member.shop.service.ISysBizActivityService;
import com.member.shop.service.ISysBizUserService;
import com.member.shop.vo.ActivityEnrollDto;
import com.member.shop.vo.ActivityOrderDetailVo;
import org.redisson.api.RDelayedQueue;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 活动Service业务层处理
 *
 * @author lixinchen
 * @date 2024-01-02
 */
@Service
public class SysBizActivityServiceImpl extends ServiceImpl<SysBizActivityMapper, SysBizActivity> implements ISysBizActivityService {
    @Resource
    private SysBizActivityMapper sysBizActivityMapper;
    @Resource
    private SysBizActivityEnrollMapper sysBizActivityEnrollMapper;
    @Resource
    private ISysBizUserService sysBizUserService;
    @Resource
    private RDelayedQueue<String> delayedQueue;
    @Resource
    private ISysBizActivityFieldService sysBizActivityFieldService;

    /**
     * 查询活动
     *
     * @param id 活动主键
     * @return 活动
     */
    @Override
    public SysBizActivity selectSysBizActivityById(Long id) {
        return sysBizActivityMapper.selectById(id);
    }

    /**
     * 查询活动列表
     *
     * @param queryWrapper 活动
     * @return 活动
     */
    @Override
    public List<SysBizActivity> selectSysBizActivityList(LambdaQueryWrapper<SysBizActivity> queryWrapper) {
        return sysBizActivityMapper.selectList(queryWrapper);
    }

    /**
     * 查询活动列表
     *
     * @param sysBizActivity 活动
     * @return 活动
     */
    @Override
    public List<SysBizActivity> selectSysBizActivityList(SysBizActivity sysBizActivity) {
        return sysBizActivityMapper.selectSysBizActivityList(sysBizActivity);

    }

    /**
     * 新增活动
     *
     * @param sysBizActivity 活动
     * @return 结果
     */
    @Override
    public int insertSysBizActivity(SysBizActivity sysBizActivity) {
        sysBizActivity.setCreateTime(DateUtils.getNowDate());
        // 将时间设置为23:59:00
        sysBizActivity.getActivityEndTime().setHours(23);
        sysBizActivity.getActivityEndTime().setMinutes(59);
        sysBizActivity.getActivityEndTime().setSeconds(59);
        return sysBizActivityMapper.insert(sysBizActivity);
    }

    /**
     * 修改活动
     *
     * @param sysBizActivity 活动
     * @return 结果
     */
    @Override
    public int updateSysBizActivity(SysBizActivity sysBizActivity) {
        sysBizActivity.setUpdateTime(DateUtils.getNowDate());
        // 将时间设置为23:59:00 修改
        if (sysBizActivity.getActivityEndTime() != null) {
            sysBizActivity.getActivityEndTime().setHours(23);
            sysBizActivity.getActivityEndTime().setMinutes(59);
            sysBizActivity.getActivityEndTime().setSeconds(59);
        }
        return sysBizActivityMapper.updateById(sysBizActivity);
    }

    /**
     * 批量删除活动
     *
     * @param ids 需要删除的活动主键
     * @return 结果
     */
    @Override
    public int deleteSysBizActivityByIds(Long[] ids) {
        return sysBizActivityMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除活动信息
     *
     * @param id 活动主键
     * @return 结果
     */
    @Override
    public int deleteSysBizActivityById(Long id) {
        SysBizActivity sysBizActivity = new SysBizActivity();
        sysBizActivity.setId(id);
        sysBizActivity.setDeleted(OrderDeleteEnum.DELETE.getKey());
        return sysBizActivityMapper.updateById(sysBizActivity);
    }

    @Override
    public List<SysBizActivity> queryActivityAll(Integer type, Integer category,Long tenantId) {
        LambdaQueryWrapper<SysBizActivity> sysBizActivityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizActivityLambdaQueryWrapper.eq(SysBizActivity::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        sysBizActivityLambdaQueryWrapper.eq(SysBizActivity::getDisplayed, EnableStatusEnum.ENABLE.getKey());
        sysBizActivityLambdaQueryWrapper.eq(SysBizActivity::getTenantId,tenantId);
        if (type != null) {

            sysBizActivityLambdaQueryWrapper.eq(SysBizActivity::getType, type);


        }
        if (category != null) {

            sysBizActivityLambdaQueryWrapper.eq(SysBizActivity::getCategory, category);

        }
        sysBizActivityLambdaQueryWrapper.orderByAsc(SysBizActivity::getStatus);
        sysBizActivityLambdaQueryWrapper.orderByAsc(SysBizActivity::getId);
        List<SysBizActivity> sysBizActivities = sysBizActivityMapper.selectList(sysBizActivityLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(sysBizActivities)) {
            List<SysBizActivity> collect = sysBizActivities.stream().filter(i -> i.getStatus() == 2).collect(Collectors.toList());
            sysBizActivities.removeIf(i -> i.getStatus() == 2);
            if (!CollectionUtils.isEmpty(collect)) {
                collect.sort(Comparator.comparing(SysBizActivity::getActivityEndTime).reversed());
                sysBizActivities.addAll(collect);
            }
        }
        return sysBizActivities;
    }

    @Override
    public SysBizActivity queryActivityById(Long id, Long userId) {
        SysBizActivity sysBizActivity = sysBizActivityMapper.selectById(id);
        if (sysBizActivity == null || sysBizActivity.getDisplayed() == 1 || sysBizActivity.getDeleted() == 1) {
            throw new ServiceException("活动已下架");
        }
        // 先判断是否登录
        if (userId == null) {
            sysBizActivity.setIsEnroll(Boolean.FALSE);
            return sysBizActivity;
        }
        LambdaQueryWrapper<SysBizActivityEnroll> sysBizActivityEnrollLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getUserId, userId);
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getActivityId, id);
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getEnrollStatus, 0);
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getPayStatus, 1);
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getActivityStartTime, sysBizActivity.getActivityStartTime());
        sysBizActivityEnrollLambdaQueryWrapper.eq(SysBizActivityEnroll::getActivityEndTime, sysBizActivity.getActivityEndTime());
        List<SysBizActivityEnroll> sysBizActivityEnrolls = sysBizActivityEnrollMapper.selectList(sysBizActivityEnrollLambdaQueryWrapper);
        sysBizActivity.setIsEnroll(!CollectionUtils.isEmpty(sysBizActivityEnrolls));
        // 报名字段
        if (sysBizActivity.getFieldId() != null) {
            SysBizActivityField sysBizActivityField = sysBizActivityFieldService.selectSysBizActivityFieldById(sysBizActivity.getFieldId());
            List<String> collect = sysBizActivityField.getFieldList().stream().filter(item -> item.getValue() == 1).map(ActivityFieldData::getName).collect(Collectors.toList());
            sysBizActivity.setFieldList(collect);
        }
        return sysBizActivity;
    }

    @Override
    public String preorder(SysBizUser loginUser, SysBizActivity sysBizActivity) {
        if (loginUser == null) {
            return "请先登录！";
        }
        if (sysBizActivity == null || sysBizActivity.getDeleted().equals(OrderDeleteEnum.DELETE.getKey())) {
            return "活动不存在！";
        }
        if (sysBizActivity.getDisplayed().equals(EnableStatusEnum.NO_ENABLE.getKey())) {
            return "活动已下架！";
        }
        if (sysBizActivity.getStatus().equals(ActivityStatusEnum.END.getKey())) {
            return "活动已结束！";
        }
        return StringUtils.EMPTY;
    }

    @Override
    public String preActivityOrder(Long userId, ActivityOrderDetailVo activityOrderDetailVo, ActivityEnrollDto activityEnrollDto, SysBizActivityEnroll sysBizActivityEnroll) {
        SysBizActivity sysBizActivity = sysBizActivityMapper.selectSysBizActivityById(activityEnrollDto.getActivityId());
        if (userId == null) {
            return "请先登录！";
        }
        if (sysBizActivity == null || sysBizActivity.getDeleted().equals(OrderDeleteEnum.DELETE.getKey())) {
            return "活动不存在！";
        }
        if (sysBizActivity.getDisplayed().equals(EnableStatusEnum.NO_ENABLE.getKey())) {
            return "活动已下架！";
        }
        if (sysBizActivity.getStatus().equals(ActivityStatusEnum.END.getKey())) {
            return "活动已结束！";
        }
        String orderCode = OrderNoCreate.activityOrderCode(OrderTypeEnum.ACTIVITY.name());
        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(userId);
        Date nowDate = DateUtils.getNowDate();
        long time = nowDate.getTime();
        String uniqueId = StringUtils.leftPad(userId.toString(), 8, "0") + time;
        String payId = "PAY" + uniqueId;
        Date date = DateUtils.addMinutes(nowDate, 15);
        sysBizActivityEnroll.setActivityId(activityEnrollDto.getActivityId());
        sysBizActivityEnroll.setActivityEnrollCode(orderCode);
        sysBizActivityEnroll.setEnrollStatus(0);
        sysBizActivityEnroll.setAmount(activityEnrollDto.getPrice());
        sysBizActivityEnroll.setActivityStartTime(sysBizActivity.getActivityStartTime());
        sysBizActivityEnroll.setActivityEndTime(sysBizActivity.getActivityEndTime());
//        sysBizActivityEnroll.setName(activityEnrollDto.getName());
//        sysBizActivityEnroll.setPhone(activityEnrollDto.getPhone());
//        sysBizActivityEnroll.setEnrollUserType(activityEnrollDto.getEnrollUserType());
        sysBizActivityEnroll.setPaymentTime(nowDate);
        sysBizActivityEnroll.setPaymentEndTime(date);
        sysBizActivityEnroll.setPayStatus(0);
        sysBizActivityEnroll.setCover(sysBizActivity.getCover());
        sysBizActivityEnroll.setUserId(sysBizUser.getId());
        sysBizActivityEnroll.setVerificationStatus(0);
        sysBizActivityEnroll.setTitle(sysBizActivity.getTitle());
        sysBizActivityEnroll.setPayId(payId);
        sysBizActivityEnroll.setCreateTime(nowDate);
        sysBizActivityEnroll.setCreateBy(sysBizUser.getNickName());
        sysBizActivityEnroll.setInfo(activityEnrollDto.getFieldList());
        // 2024 0327 新增四个报名固定字段
//        sysBizActivityEnroll.setIdCard(activityEnrollDto.getIdCard());
//        sysBizActivityEnroll.setDivideGroup(activityEnrollDto.getDivideGroup());
//        sysBizActivityEnroll.setReference(activityEnrollDto.getReference());
//        sysBizActivityEnroll.setRemark(activityEnrollDto.getRemark());
        sysBizActivityEnrollMapper.insert(sysBizActivityEnroll);
        BeanUtils.copyProperties(sysBizActivityEnroll, activityOrderDetailVo);
        // 将数据存入redisson队列
        String key = "ACTIVITY_" + payId;
        delayedQueue.offerAsync(key, 60 * 15, TimeUnit.SECONDS);
        return StringUtils.EMPTY;
    }
}
